export interface Cache {
  key: string
  value: string
}

export const useCacheStore = defineStore('app-cache', () => {
  const cacheList = ref<Cache[]>([])

  /**
   * 获取缓存
   * @param key 关键字
   */
  const getCacheValue = (key: string) => {
    if (key) {
      for (const cache of cacheList.value) {
        if (cache.key === key) {
          return cache.value
        }
      }
    }

    return null
  }

  /**
   * 删除缓存
   * @param key 关键字
   */
  const removeCacheValue = (key: string) => {
    if (key) {
      cacheList.value = cacheList.value.filter((item) => {
        return item.key !== key
      })
    }
  }

  /**
   * 设置缓存
   * @param key 缓存Key
   * @param value 缓存Value
   */
  const set = async (key: string, value: any) => {
    // 获取用户信息
    if (key && value) {
      removeCacheValue(key)

      const cacheJson = JSON.stringify(value)
      cacheList.value.push({ key, value: cacheJson })
    }
  }

  /**
   * 获取缓存
   * @param key 缓存Key
   */
  const get = async (key: string) => {
    // 获取缓存JSON
    const cacheJson = getCacheValue(key)
    try {
      // 转化JSON
      return cacheJson ? JSON.parse(cacheJson) : null
    } catch (e) {
      console.error('Cache::get', e)
      return null
    }
  }

  /**
   * 设置缓存
   * @param key 缓存Key
   * @param value 缓存Value
   * @param expires 缓存失效时间（秒）
   */
  const setByExpires = async (key: string, value: any, expires: number) => {
    // 获取用户信息
    if (key && value && expires) {
      const keyByExpires = `expires_${key}`
      const valueExp = {
        expires: new Date().getTime() + expires * 1000,
        value,
      }
      removeCacheValue(key)

      const cacheJson = JSON.stringify(valueExp)
      cacheList.value.push({ key: keyByExpires, value: cacheJson })
    }
  }

  /**
   * 获取缓存
   * @param key 缓存Key
   */
  const getByExpires = async (key: string) => {
    // 设置有效期的缓存key
    const keyByExpires = `expires_${key}`
    // 获取key的Value
    const cacheJson = getCacheValue(keyByExpires)

    if (!cacheJson) {
      return null
    }

    // 获取key的Value
    try {
      const valueExp = JSON.parse(cacheJson)
      if (valueExp.expires < new Date().getTime()) {
        removeCacheValue(keyByExpires)
        return null
      }
      return valueExp.value
    } catch (e) {
      console.error('Cache::getByExpires', e)
      return null
    }
  }

  return {
    cacheList,
    set,
    get,
    setByExpires,
    getByExpires,
  }
}, { persist: true })
